import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { checkedInput } from "@/utils/public/regular"
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import {
  proinsureGetDetail,
  ProinsureApplyInsure,
  proinsureGetProduct,
  ProProductsGetProProducts
} from "@/api/stu/InsuranceData"
import qs from "qs";
export function useApplyInsurance() {
  const route = useRoute();
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "保险产品名称",
      prop: "ppName",
    },
    {
      label: "保险类型",
      prop: "pType",
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const stubims = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [10, 30, 50, 100],
    background: true
  });
  const lodingType = ref<string>("")
  const dataList = ref([]);
  const loading = ref(false);
  const DialogVisible = ref<boolean>(false);
  const Refstubim_from = ref();
  const active_cart = ref("1")
  const ProductName = ref();//产品名称
  const insuranceProductList = ref([]);//保险产品名称列表
  const insureDetailList = ref([]); // 投保详情列表
  const btnloading = ref<boolean>(false);
  const ServiceLife = [
    {
      label: "0-1年",
      value: "0-1年"
    },
    {
      label: "1年",
      value: "1年"
    }, {
      label: "2年",
      value: "2年"
    }, {
      label: "3年",
      value: "3年"
    }, {
      label: "4年",
      value: "4年"
    }, {
      label: "5年",
      value: "5年"
    }, {
      label: "6年",
      value: "6年"
    }, {
      label: "7年",
      value: "7年"
    }, {
      label: "8年",
      value: "8年"
    }, {
      label: "9年",
      value: "9年"
    }, {
      label: "10年",
      value: "10年"
    }, {
      label: "11年",
      value: "11年"
    }, {
      label: "12年",
      value: "12年"
    }, {
      label: "13年",
      value: "13年"
    }, {
      label: "14年",
      value: "14年"
    },
  ]
  const accidentsNum = [
    {
      label: "4年及以上无赔",
      value: "4年及以上无赔"
    }, {
      label: "3年无赔",
      value: "3年无赔"
    }, {
      label: "2年无赔，3年1次",
      value: "2年无赔，3年1次"
    }, {
      label: "上年无赔，2年1次，3年2次",
      value: "上年无赔，2年1次，3年2次"
    }, {
      label: "新车，上年1次，2年2次，3年3次",
      value: "新车，上年1次，2年2次，3年3次"
    }, {
      label: "1年2次，2年3次，3年4次",
      value: "1年2次，2年3次，3年4次"
    }, {
      label: "1年3次，2年4次，3年5次",
      value: "1年3次，2年4次，3年5次"
    }, {
      label: "1年4次，2年5次，4年6次",
      value: "1年4次，2年5次，4年6次"
    }, {
      label: "1年5次，2年6次，3年7次",
      value: "1年5次，2年6次，3年7次"
    }, {
      label: "1年6次，2年7次，3年8次",
      value: "1年6次，2年7次，3年8次"
    }
  ]
  const Caruse = ref([
    { label: "党政机关、事业团体", value: "党政机关、事业团体", cstate: '1' },
    { label: "企业", value: "企业", cstate: "1" },
    // <!--营业用  -->
    { label: "出租单位", value: "出租单位", cstate: "2" },
    { label: "租赁单位", value: "租赁单位", cstate: "2" },
    { label: "城市公交", value: "城市公交", cstate: "2" },
    { label: "公路客运", value: "公路客运", cstate: "2" },
    // 特种车型
    { label: "特种车型一", value: "特种车型一", cstate: "3" },
    { label: "特种车型二", value: "特种车型二", cstate: "3" },
    { label: "特种车型三", value: "特种车型三", cstate: "3" },
    { label: "特种车型四", value: "特种车型四", cstate: "3" },
  ])
  const carttype = [
    { label: "家庭自用车", value: "家庭自用车", cstate: '4' },
    { label: "非营业用客车", value: "非营业用客车", cstate: '1' },
    { label: "营业用客车", value: "营业用客车", cstate: '2' },
    { label: "非营业用货车", value: "非营业用货车", cstate: '6' },
    { label: "营业用货车", value: "营业用货车", cstate: '5' },
    { label: "特种车型", value: "特种车型", cstate: '3' },
  ]
  const rules = {
    piApplicant: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.chineseName[0].test(value)) {
            // console.log("1")
            return callback(new Error('请输2-6个字中文名称'))
          } else {
            return callback()
          }
        }, trigger: ['change', 'blur']
      }

    ],
    applicantAge: [
      // { required: true, type: 'number', message: '请输入年龄', trigger: ['change', 'blur'] },
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value < 18) {
            // console.log("2")
            return callback(new Error('投保人年龄不能小于18岁'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    applicantSex: [
      { required: true, message: '请选择性别', trigger: ['change', 'blur'] },
    ],
    idCard: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.idCardNo[0].test(value)) {
            // console.log("3")
            return callback(new Error('请输正确的身份证号'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    phone: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.phone[0].test(value)) {
            // console.log("4")
            return callback(new Error('请输正确的手机号码'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],

    assured: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.chineseName[0].test(value)) {
            // console.log("5")
            return callback(new Error('请输2-6个字中文名称'))
          } else {
            return callback()
          }
        }, trigger: ['change', 'blur']
      }
    ],
    assuredAge: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value < 18) {
            // console.log("6")
            return callback(new Error('被投保人年龄不能小于18岁'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    assuredSex: [
      { required: true, message: '请选择性别', trigger: ['change', 'blur'] },
    ],
    assuredIDCard: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.idCardNo[0].test(value)) {
            // console.log("7")
            return callback(new Error('请输正确的身份证号'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    applyTime: [
      { required: true, message: '请选择申请时间', trigger: ['change', 'blur'] },
    ],
    carType: [
      { required: true, message: '请选择车辆类型', trigger: ['change', 'blur'] },
    ],
    carUse: [
      { required: true, message: '请选择车辆用途', trigger: ['change', 'blur'] },
    ],
    seatTonnage: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          // console.log("value", value)
          // console.log("ApplyForm.carType", ApplyForm.carType.cstate)
          if (ApplyForm.carType.cstate == '4' || ApplyForm.carType.cstate == '1' || ApplyForm.carType.cstate == '2') {
            if (value < 1 || value > 74) {
              // console.log("8")
              return callback(new Error('请输正确的座位数(1-74)'))
            } else {
              return callback()
            }
          } else if (ApplyForm.carType.cstate == '6' || ApplyForm.carType.cstate == '3') {
            if (value < 1.8 || value > 44) {
              // console.log("9")
              return callback(new Error('请输正确的吨数(1.8-44)'))
            } else {
              return callback()
            }
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    carUseYear: [
      { required: true, message: '请选择车辆使用年限', trigger: ['change', 'blur'] },
    ],
    buyCarPrice: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (!checkedInput.number[0].test(value)) {
            return callback(new Error('仅可输入数字'))
          } else if (value < 50000 || value > 10000000) {
            // console.log("10")
            return callback(new Error('输入5万≤购置价≤1000万'))
          } else {
            return callback()
          }
        },
        trigger: ['change', 'blur']
      }
    ],
    count: [
      { required: true, message: '请选择出险次数', trigger: ['change', 'blur'] },
    ]
  };
  const ApplyForm = reactive<any>(
    {
      pType: "",  //保险类型
      ppName: "",    //保险产品
      piApplicant: "",  //投保人
      applicantAge: null,   //投保人年龄
      applicantSex: "",  //投保人性别
      carType: "",  //车辆类别
      carUse: "",   //车辆用途
      seatTonnage: null,   //座位数/吨位数
      carUseYear: "",  //车辆使用年限
      buyCarPrice: "",  //新车购置价
      count: "",    //出险次数
      idCard: "",   //身份证
      phone: "",   //电话号码
      assured: "",   //被保险人姓名
      assuredAge: null,  //被保险人年龄
      assuredSex: "",   //被保险人性别
      assuredIDCard: "",   //被保险人身份证
      applyTime: "",   //申请时间
      details: [
        {
          projectName: "",   //保障项目
          range: "",   //保险范围
          price: "",   //保障金额
          pSelect: ""   //选择
        }
      ]
    }
  );

  // 获取投保方案的投保名称列表
  async function getProductNameList(row) {
    const res = await proinsureGetProduct(qs.stringify({ PType: row.pType }));
    if (res.success) {
      insuranceProductList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  //获取投保方案的详情列表
  async function GetDetailList(row) {
    const data = qs.stringify({ pid: row })
    const res = await proinsureGetDetail(data);
    stubims.value = []
    insureDetailList.value = []
    if (res.success) {
      let arry = []
      let arrys = []
      res.data.forEach(r => {
        r.ranges.forEach(e => {
          arrys.push({ ...e, ...{ project: r.project } })
          arry.push({
            projectName: "",   //保障项目
            range: "",   //保险范围
            price: "",   //保障金额
            pSelect: []   //选择
          })
        })
      })
      stubims.value = arry
      console.log("123", arry)
      insureDetailList.value = arrys

    } else {
      ElMessage.error(res.msg)
    }
  }

  //申请投保
  async function Apply(row) {
    getProductNameList(row)
    GetDetailList(row.ppId)
    DialogVisible.value = true;
    ProductName.value = row.ppName;
    lodingType.value = row.pType
  }

  // 提交申请表单
  function stubim_from(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      let data = null
      let ismArry = [];
      let istate = 0;
      for (let k in stubims.value) {
        // TODO:将空的二维数组去掉
        if (!stubims.value[k].pSelect[0]?.length) stubims.value[k].pSelect = [];
        ismArry.push(stubims.value[k].pSelect);
        data = {
          taskId: route.query.taskId,
          planId: route.query.planId,
          ...ApplyForm,
          ...{
            carType: ApplyForm.carType.value,
            details: stubims?.value,
            pType: lodingType.value,
            ppName: ProductName.value
          }
        };
      };
      ismArry.forEach(el => { if (el[0]?.length) istate = 1; })
      if (!istate) {
        ElMessage.warning("选填完整投保方案")
        return
      }
      btnloading.value = true;
      const res = await ProinsureApplyInsure(data);
      if (res.success) {
        ElMessage.success(res.msg)
        close_from(row)
        btnloading.value = false;
      } else {
        ElMessage.error(res.msg)
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    })
  }

  // 关闭弹窗
  function close_from(row: FormInstance | undefined) {
    row.resetFields();
    lodingType.value = "";
    ProductName.value = "";
    active_cart.value = '1';// 默认投保信息
    insureDetailList.value = [];
    DialogVisible.value = false
  }
  function handleSizeChange(val) {
    getDataList()
  }

  function handleCurrentChange(val) {
    getDataList()
  }

  async function getDataList() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    }
    const res = await ProProductsGetProProducts(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }


  onMounted(() => {
    getDataList()
  })
  return {
    rules, stubims,
    loading,
    columns,
    ServiceLife,
    accidentsNum,
    Caruse,
    btnloading,
    carttype,
    dataList,
    ApplyForm,
    pagination,
    lodingType,
    active_cart,
    ProductName,
    DialogVisible,
    Refstubim_from,
    insureDetailList,
    insuranceProductList,
    Apply,
    close_from,
    stubim_from,
    handleSizeChange,
    handleCurrentChange
  }
}
